package com.hhf.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hhf.springboot.annotation.AuthCheck;
import com.hhf.springboot.common.*;
import com.hhf.springboot.constant.UserConstant;
import com.hhf.springboot.exception.BusinessException;
import com.hhf.springboot.exception.ThrowUtils;
import com.hhf.springboot.model.dto.fileInfo.FileInfoQueryRequest;
import com.hhf.springboot.model.entity.FileInfo;
import com.hhf.springboot.model.entity.User;
import com.hhf.springboot.model.vo.FileInfoVO;
import com.hhf.springboot.service.FileInfoService;
import com.hhf.springboot.service.UserService;
import com.hhf.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 文件信息接口
 *
 * @author tws
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/11/20
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileInfoController {

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        return Result.success(fileInfoService.upload(file,request));
    }

    /**
     * 下载文件
     * @param fileUUID
     * @param response
     * @return
     */
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        fileInfoService.download(fileUUID, response);
    }

    /**
     * 删除文件信息
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteFileInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        FileInfo oldFileInfo = fileInfoService.getById(id);
        ThrowUtils.throwIf(oldFileInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldFileInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = fileInfoService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }


    /**
     * 根据 id 获取文件信息（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<FileInfoVO> getFileInfoVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        FileInfo fileInfo = fileInfoService.getById(id);
        ThrowUtils.throwIf(fileInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(fileInfoService.getFileInfoVO(fileInfo, request));
    }

    /**
     * 分页获取文件信息列表（仅管理员可用）
     *
     * @param fileInfoQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<FileInfo>> listFileInfoByPage(@RequestBody FileInfoQueryRequest fileInfoQueryRequest) {
        long current = fileInfoQueryRequest.getCurrent();
        long size = fileInfoQueryRequest.getPageSize();
        // 查询数据库
        Page<FileInfo> fileInfoPage = fileInfoService.page(new Page<>(current, size),
                fileInfoService.getQueryWrapper(fileInfoQueryRequest));
        return Result.success(fileInfoPage);
    }

    /**
     * 分页获取文件信息列表（封装类）
     *
     * @param fileInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<FileInfoVO>> listFileInfoVOByPage(@RequestBody FileInfoQueryRequest fileInfoQueryRequest,
                                                               HttpServletRequest request) {
        long current = fileInfoQueryRequest.getCurrent();
        long size = fileInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<FileInfo> fileInfoPage = fileInfoService.page(new Page<>(current, size),
                fileInfoService.getQueryWrapper(fileInfoQueryRequest));
        // 获取封装类
        return Result.success(fileInfoService.getFileInfoVOPage(fileInfoPage, request));
    }

    /**
     * 分页获取当前登录用户创建的文件信息列表
     *
     * @param fileInfoQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<FileInfoVO>> listMyFileInfoVOByPage(@RequestBody FileInfoQueryRequest fileInfoQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(fileInfoQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        fileInfoQueryRequest.setUserId(loginUser.getId());
        long current = fileInfoQueryRequest.getCurrent();
        long size = fileInfoQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<FileInfo> fileInfoPage = fileInfoService.page(new Page<>(current, size),
                fileInfoService.getQueryWrapper(fileInfoQueryRequest));
        // 获取封装类
        return Result.success(fileInfoService.getFileInfoVOPage(fileInfoPage, request));
    }

    /**
     * 日新增统计任务管理信息
     *
     * @return
     */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedFile() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> taskDataList = fileInfoService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(taskDataList);

    }


}
